package controller;

import exception.OtherException;
import exception.SomeException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/7/29 11:43
 * Version:1.0-SNAPSHOT
 * Description:
 */
@Controller
@RequestMapping("/exception")
public class ExceptionController {

    // 当方法被@ExceptionHandler进行标注
    // 表示当当前Controller中的某一个方法遇到了异常之后
    // 会进入到该方法进行处理
    // 该注解可以传递异常类型,默认为Exception
//    @ExceptionHandler(SomeException.class)
//    public ModelAndView exceptionHandler(Exception e){
//        ModelAndView mav = new ModelAndView();
//        mav.setViewName("exception");
//        mav.addObject("e",e);
//        return mav;
//    }
//    @ExceptionHandler(OtherException.class)
//    public ModelAndView exceptionHandler2(Exception e){
//        ModelAndView mav = new ModelAndView();
//        mav.setViewName("exception2");
//        mav.addObject("e",e);
//        return mav;
//    }

    @ExceptionHandler
    public ModelAndView exceptionHandler(Exception e){
        ModelAndView mav = new ModelAndView();
        mav.addObject("e",e);
        if(e instanceof SomeException){
            mav.setViewName("exception");
        } else if(e instanceof OtherException){
            mav.setViewName("exception2");
        } else{
            mav.setViewName("exception2");
        }
        return mav;
    }

    @RequestMapping("/f1")
    public void f1() throws SomeException {
        System.out.println("ExceptionController.f1");
        throw new SomeException("执行ExceptionController中的f1方法遇到了异常");
    }

    @RequestMapping("/f2")
    public void f2() throws OtherException {
        System.out.println("ExceptionController.f2");
        throw new OtherException("执行ExceptionController中的f2方法遇到了异常");
    }

    @RequestMapping("/f3")
    public void f3(){
        int i = 1/0;
    }

}
